class WatermarkController < ApplicationController

  require 'oci8'
  require 'libxml'

  #Helper method to use a python-like generator
  def to_generator(*args)
    Enumerator.new do |enum|
      args.each {|c|
      while r=c.fetch
        enum.yield r      
      end
      }
    end
  end

  def addControlfield(record, tag, text)
    record<< controlfield=LibXML::XML::Node.new("controlfield")
    controlfield["tag"]=tag
    controlfield.content=String(text)
  end

  def addDatafield(record, tag)
    record<< datafield=LibXML::XML::Node.new("datafield")
    datafield["tag"]=tag
    datafield["ind1"]="  "
    datafield["ind2"]="  "
    datafield
  end

  def addSubfield(datafield, code, text)
    datafield<< subfield=LibXML::XML::Node.new("subfield")
    subfield["code"]=code
    subfield.content=String(text)
  end

  #Retrieve watermark-relevant stuff from OracleRDBMS in MarcXML
  #Uses ss_mm temporary table as
  # create table ss_mm as select pr_isn, to_lob(text) from mmtxpd where feld='A0675'
  #Fields: ISN, Title, Description, URL, updated, short title and RISM-ID from musical sources
  #
  def to_marcxml()
    conn=OCI8.new('rism1','rism1','//rism-online.info:1521/orcl')
    sql='select
    M.MOISN,
    coalesce(group_concat(hs.wasser), M.MOTITL),
        to_char(s.text),
    h.kutit,
    h.rismnr,
    M.MOUPDD, group_concat(hs.wasser),M.MOISN, substr(h.h02035,1,4)||\'-\'||substr(h.h02040,1,4)
        from mmprpd M inner join ss_mm S on (m.moisn=s.pr_isn)
    inner join hss001 hs on (hs.indkey=m.moisn)
    inner join hspr01 h on (hs.pr_isn=h.h0001)
        where M.MOTYP=\'JPG\'
        and M.MOTITL like \'%_wm%\' or M.MOTITL like \'WZ%\'     
    group by M.MOISN, M.MOTITL, to_char(s.text),h.kutit, h.rismnr,  M.MOUPDD,substr(h.h02035,1,4)||\'-\'||substr(h.h02040,1,4)' 
        
    sql2='select replace(s.rowid, \'/\',\'\'),s.wasser,NULL,h.kutit,
    h.rismnr, h.adatum,NULL,NULL,substr(h.h02035,1,4)||\'-\'||substr(h.h02040,1,4)
    from hss001 s inner join hspr01 h on (h.h0001=s.pr_isn)
    where h.rismnr is not NULL and s.indkey is NULL and s.wasser is not NULL  
    union
    select replace(s.rowid, \'/\',\'\'),s.wasser,NULL,h1.kutit,
        h1.rismnr, h1.adatum,NULL,NULL,substr(h1.h02035,1,4)||\'-\'||substr(h1.h02040,1,4)
        from hss001 s inner join hspr01 h1 on (h1.h0001=s.hswkey)    
        where s.hswkey  is not NULL and h1.rismnr is not NULL and s.indkey is NULL and s.wasser is not NULL  
    
    '

    c=conn.exec(sql)
    c2=conn.exec(sql2)
    @result=to_generator(c,c2)
    @xml=LibXML::XML::Document.new()
    @xml.root = LibXML::XML::Node.new("collection")
    LibXML::XML::Namespace.new(@xml.root, nil,'http://www.loc.gov/MARC21/slim')
    
    
    @result.each {|i|
      @xml.root << record=LibXML::XML::Node.new("record")
      record<<leader=LibXML::XML::Node.new("leader")
      #Dummy leader
      leader.content='01297nz  a2200421   4500'
      addControlfield(record, '001', i[0])
    addControlfield(record, '005', i[5])
  #title
    data=addDatafield(record, '100'); addSubfield(data, 'a', String(i[1]).encode("ISO-8859-1"))
#year
  if i[8]
       data=addDatafield(record, '260');addSubfield(data, 'c', i[8])
     end
     #descriptio
if i[2]
       data=addDatafield(record, '500');addSubfield(data, 'a', i[2])
     end
     #description in source
      if i[6]
      data=addDatafield(record, '590'); addSubfield(data, 'a', String(i[6]).strip)
end
#link to musical source
data=addDatafield(record, '762'); addSubfield(data, 'a', String(i[3].encode("ISO-8859-1").split(':')[0] ).strip);addSubfield(data, 'w', i[4])
#Image
if i[7]      
data=addDatafield(record, '856'); addSubfield(data, 'u','http://dl.rism.info/DO/'+ String(i[7])+'.jpg')
end
    }
    @xml.save('app/assets/watermark.xml')
    
    
  end

def sru
  @name=nil
  require 'libxml'  
  require 'libxslt'
  dn ='dn:http://www.loc.gov/MARC21/slim'
  fac ='fac:http://www.indexdata.com/zebra/'
  
  #Helper method to get ZEBRA-facet for the result set
  #IMPORTANT: Zebra facects are not relieable at the moment
  #Parameters: XML-Document, Namespace, Indexfield
  def getFacet(doc, dn, index)
      facet_place=doc.find('//fac:record/fac:facet[@index="'+index+'"]/fac:term[@occur]',dn).to_a[0..4]
          f_place=[]
          facet_place.each {|node|
            if node.content.size>1
              content=node.content.capitalize
            else
              content=node.content
            end
            f_place << [content, "("+node['occur']+")"]
          }
          f_place
  end
   
 #Helper method to convert SRU-search parameter to SOLR-search parameter
def sru2solr(text)
  res=[]
  if !text.include?('=')
    res<< text
  elsif text.split('=').size==2
    if text.split('=')[1].include?('*')
    res << text.split('=')[0]+':'+text.split('=')[1]
else
res << text.split('=')[0]+':"'+text.split('=')[1]+'"'
end
  else
    res<<text.split('=')[0]+':'
    text.split('=')[1..-1].each {|v|
      if v.include?(" and ")
        if v.split('and')[0].include?('*')
        res <<v.split('and')[0].strip
      else
        res <<'"'+ v.split('and')[0].strip+'"'
end
        res << "AND"
        res<<v.split('and')[1]+':'
      else
        if v.include?('*')
          res << v
        else
          res << '"'+v+'"'
        end
      end
    }
  end
  res.join(' ').gsub(' and ',' AND ')
end
     
def getSolrFacet(doc, index)
    facet_place=doc.find('//lst/lst/lst[@name="'+index+'"]/child::node()').to_a
        f_place=[]
        facet_place.each {|node|
          node.each {|e|
            if node.content.to_i>0
              if node["name"].size>1
                            content=node["name"].capitalize
              else
                content=node["name"]
              end
          f_place << [content,"("+String(node.content)+")"]
          end 
          }
        }
        f_place
end
        
  
  @para=params
  if params["sru"]
  @par=params
  @name=params["sru"]["name"] if params["sru"]["name"]
   
  end
  @start=params["start"] if params["start"]
    
    def pager(n)
      l=[1]
      l+=(1..(n/20)).map {|i|i*20+1}
       l
    end
    
    
    
    
  url='http://lab.rism.info:9910/watermark?operation=searchRetrieve&version=1.1&query='+String(@name)+'&maximumRecords=20&startRecord='+String(@start)
  xml_document =LibXML::XML::Document.file(url)
  
  
if params["sru"]
  #@solr_facet_url='http://lab.rism.info:8080/solr/person/select/?q='+sru2solr(@name)+'&version=2.2&start=0&rows=0&indent=on&facet=true&facet.field=place&facet.field=country&facet.field=profession&facet.field=gender&facet.limit=6'
  #solr_facet_document =LibXML::XML::Document.file(@solr_facet_url)

  #@facet_place=getSolrFacet(solr_facet_document,'place')
  #@facet_profession=getSolrFacet(solr_facet_document,'profession')
  #@facet_gender=getSolrFacet(solr_facet_document,'gender')
  #@facet_country=getSolrFacet(solr_facet_document,'country')


end  

  
  @count=xml_document.find('//zs:numberOfRecords/text()')[0]
  if @count
    @pager=pager(@count.to_s.to_i)
    @actual=(@pager[@pager.index(@start.to_i)-2..@pager.index(@start.to_i)]+@pager[@pager.index(@start.to_i)..@pager.index(@start.to_i)+2]).uniq 
    @next=@pager[@pager.index(@start.to_i)+1]
    @previous=@pager[@pager.index(@start.to_i)-1]
  end
  
  style='/home/stephan/workspace/RISMToolKit/app/assets/watermark.xsl'
  stylesheet_doc=LibXML::XML::Document.file(style)
  stylesheet=LibXSLT::XSLT::Stylesheet.new(stylesheet_doc)
  @res=stylesheet.apply(xml_document)  
  
end

  
  def show()

  end

end
